<?php
declare (strict_types=1);

namespace app\model;

use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

/**
 * 文章模型
 * Class PortalArticle
 *
 * @property int $aid 文章编号
 * @property int $click 点击数
 * @property int $collect
 * @property int $likes 喜欢数
 * @property int $mod 附属模块
 * @property int $status 状态
 * @property int $tid 文章所属栏目
 * @property int $uid 发表用户
 * @property int $ulikes 不喜欢数
 * @property string $create_time 创建时间
 * @property string $description 文章简介
 * @property string $litpic 文章封面
 * @property string $thumb 缩略图
 * @property string $title 标题
 * @property string $update_time 更新时间
 * @property-read \app\model\PortalAddonarticle $addonarticle
 * @property-read \app\model\PortalMenu $menu
 * @package app\common\model
 */
class PortalArticle extends Model
{
    protected $pk = 'aid';


    public function addonarticle(): \think\model\relation\HasOne
    {
        return $this->hasOne(PortalAddonarticle::class, 'aid');
    }

    public function menu(): \think\model\relation\HasOne
    {
        return $this->hasOne(PortalMenu::class, 'tid','tid');
    }

    /**
     * 获取文章内容
     * @param int $aid
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getArticle(int $aid)
    {
        return self::cache(true)->find($aid);
    }

    /**
     * 获取文章列表
     * @param int|array $tid
     * @param string $type
     * @param int $row
     * @param string $order
     * @return array|PortalArticle|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getList(int|array $tid, string $type, int $row = 99, string $order = 'create_time desc'): \think\Collection|array
    {
        $where = [];
        //栏目编号筛选
        if (!empty($tid)) {
            if (is_array($tid)) {
                $where[] = ['tid', 'in', $tid];
            } else {
                $where[] = ['tid', '=', $tid];
            }
        }

        return self::where($where)->order($order)->cache(true, 600)->limit($row)->select();
    }


    public function getUrlAttr($value, $data): \think\route\Url
    {
        return url("aid/" . $data['aid']);
    }
}
